// Copyright (c) 2008-2010, Arne Claus
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the 
// following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following 
//   disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following 
//   disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name Arne Claus nor the names of any contributors may be used to endorse or promote products
//   derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef __INCLUDED_CBL_MEMORY_H__
#define __INCLUDED_CBL_MEMORY_H__

#include "CBL_Defines.h"
#include "CBL_Math.h"
#include <cstdlib>

CB_SUBNAMESPACE_START(Memory)

template<typename TClass>
CB_FORCEINLINE void CB_INLINE_ATTR SafeDelete(TClass*& _rpObject)
{
	if (_rpObject)
	{
		delete(_rpObject);
		_rpObject = NULL;
	}
}

// -------------------------------------------------------------------------------------------------

//! /note	Tries to allocate memory so that memory fragmentation is kept at a low level.
//!			This will create larger allocations than necessary as it will always try to allocate
//!			The next higher power of two number of bytes if the allocation size is below 16KB.
BASELIB_API void* AllocLowFragemtation(memint _Size);

//! /note	Allocates memory aligned to _Alignment Bytes. So if _Alignment is 128, the pointer adress returned
//!			modulo 128 will be 0.
//!			The allocated size will always bei _Size + _Alignment, offset information will be stored one 
//!			byte before the returned adress.
BASELIB_API void* AllocAligned(memint _Size, uint8 _Alignment);

//! /note	Deallocates aligned memory
BASELIB_API void DeAllocAligned(void* _pObject);

//!	/note	Like AllocAligned, only for arrays.
BASELIB_API void* ArrayAllocAligned(memint _Size, uint8 _Alignment);

//! /note	Like DeAllocAligned, only for arrays.
CB_FORCEINLINE void CB_INLINE_ATTR ArrayDeAllocAligned(void* _pObject);

CB_SUBNAMESPACE_END

#endif